package com.ymdx.action;

import com.opensymphony.xwork2.ModelDriven;
import com.ymdx.entity.Label;
import com.ymdx.service.LabelService;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 新闻标签
 * Created by yangliwei on 2017/8/16.
 */
public class LabelAction extends GenericActionSupport implements ModelDriven<Label> {
    private Label label;

    @Resource
    private LabelService labelService;

    /**
     * 获取全部标签
     *
     * @return
     */
    @Action(value = "/label/all", results = @Result(name = SUCCESS, type = JSON, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\[\\d+\\]\\.id,data\\[\\d+\\]\\.name"
    }))
    public String all() {
        Label param = new Label();
        List<Label> labels = labelService.getByExample(param);
        responseTool.setStatus(1);
        responseTool.setData(labels);
        return SUCCESS;
    }

    @Action(value = "/admin/label/save", results = @Result(name = SUCCESS, type = JSON, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\[\\d+\\]\\.id,data\\[\\d+\\]\\.name"
    }))
    public String save() {
        if (label.getName() == null) {
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        label.setCreateTime(new Date());
        labelService.save(label);
        responseTool.setStatus(1);
        responseTool.setData(label);
        return SUCCESS;
    }

    @Action(value = "/admin/label/delete", results = @Result(name = SUCCESS, type = JSON, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data"
    }))
    public String delete() {
        Long id = label.getId();
        if(id == null){
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        Label oldLabel= labelService.getById(Label.class,id);
        if(oldLabel == null){
            responseTool.setStatus(0);
            responseTool.setCode("course_not_exist");
            return SUCCESS;
        }
        labelService.delete(oldLabel);
        return SUCCESS;
    }


    @Override
    public Label getModel() {
        if (label == null) {
            label = new Label();
        }
        return label;
    }
}
